#include "addstu.h"
#include "ui_addstu.h"
#include <QString>
#include <QDebug>
#include <QMessageBox>
#include <QPushButton>
#include <QList>
#include <QAbstractButton>
#include <QIODevice>
#include <QFile>
#include <QTextStream>
addStu::addStu(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::addStu)
{
    ui->setupUi(this);
}

addStu::~addStu()
{
    delete ui;
}

void addStu::on_btn_ok_clicked()
{
    QString name = this->ui->le_name->text();
    QString id = this->ui->le_id->text();
    //checkedButton()返回一个按钮的指针，返回了一个被选中的按钮。可以获取这个按钮的文本。
    QString sex = this->ui->sexGroup->checkedButton()->text();
    //它返回的是按钮组里面所有按钮的集合(处理多选按钮的按钮组)
    //因为返回的是QList<QAbstractButton *>类型所以要加以<QList><QAbstractButton>
    QList<QAbstractButton *> ins_list = this->ui->insGroup->buttons();
    QString ins;
    int i = 0;
    for(i = 0;i < ins_list.length();i++){
        QAbstractButton * che = ins_list.at(i);
        if(che->isChecked()){
            ins += che->text() + " ";
        }
    }
//获取年龄下拉框当前值
    QString age = this->ui->cbb_age->currentText();
    //获取学院下拉框当前值
        QString dev = this->ui->cbb_yx->currentText();
    QString content = name + '\n' + id + '\n' + sex + '\n' + age  + '\n'+dev+ '\n' + ins;
    //为了把数据传入文件，需要重新建一个QString字符串
    QString cnt = name + " " + id + " " + sex + " " + age + " " + dev + " " + ins + "\n";

    if(name.length() < 1 || id.length() < 1 || ins.length() < 1){
        QMessageBox::critical(this,"错误","信息填写不完整，请重新检查","确认");
    }else{
        int ret = QMessageBox::information(this,"请确认信息",content,"确认","取消");
        if(ret == 0){
            //当点击确认后还原所有选项
            clearUserInterface();
            //把数据传入文件
            writeToFile(cnt);
        }
    }
}

void addStu::clearUserInterface(){
    this->ui->le_name->clear();
    this->ui->le_id->clear();
    this->ui->rbtn_male->setChecked(true);
    this->ui->cbb_age->setCurrentIndex(0);
    this->ui->cbb_yx->setCurrentIndex(0);
    QList<QAbstractButton *> ins_list = this->ui->insGroup->buttons();
    int i = 0;
    for(i = 0;i < ins_list.length();i++){
        QAbstractButton * box = ins_list.at(i);
        box->setChecked(false);
    }
    this->ui->le_name->setFocus();
}

//把数据传入文件
void addStu::writeToFile(QString cnt){
    QFile file("stu.txt");
    if (!file.open(QIODevice::Append | QIODevice::Text)){
        //如果文件没打开会弹出这个框
        QMessageBox::critical(this,"错误","文件打开失败，信息没有保持！","确认");
        return;
    }
    QTextStream out(&file);
    out << cnt;
    file.close();
}
void addStu::on_btn_cancel_clicked()
{
    this->close();
}
